<?php

/**
 * 商品报名管理
 * File Name：GoodsbmController.php
 * File Encoding：UTF-8
 * File New Time：2014-5-7 10:07:59
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class GoodsbmController extends AdminBase {

    //待审核总数
    public $waitHeckSum = 50;
    //每次获取审核数
    public $waitHeckCount = 20;

    //报名列表
    public function actionIndex($wher = array()) {
        //搜索
        if (IS_POST) {
            foreach ($_POST as $k => $v) {
                if ($v == '') {
                    unset($_POST[$k]);
                }
            }
            $this->redirect(self::U(Yii::app()->getController()->getAction()->id, $_POST));
            exit;
        }
        //自动跳转到自己主要负责的栏目
        if (self::$userInfo['cat_id'] && !isset($_GET['cat_id'])) {
            $this->redirect(self::U(Yii::app()->getController()->getAction()->id, array('cat_id' => self::$userInfo['cat_id'])));
        }
        //分页
        $pageId = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        //分页数
        $limit = 20;
        //报名模型
        $model = GoodsBmModel::model();
        //条件数组
        $where = !empty($wher) ? $wher : $this->setWhere(array('item_type' => array('LT', 10)));
        if (!isset($_GET['status'])) {
            unset($where['isdelivery']);
        }
        $criteria = $model->where($where);
        //信息总数
        $key = md5(serialize($where));
        $cacheCount = Yii::app()->cache->get($key);
        if (empty($cacheCount)) {
            $cacheCount = $model->count($criteria);
            Yii::app()->cache->set($key, $cacheCount, 300);
        }
        $count = $cacheCount;
        //分页
        $page = self::page($count, $limit, $pageId);
        //查询信息
        $criteria->limit = $page->listRows;
        $criteria->offset = $page->firstRow;
        $data = $model->findAll($criteria);

        $this->assign("Page", $page->show());
        $this->assign('data', $data);
        $this->assign('count', $count);
        $this->render('index');
    }

    //审核通过
    public function actionPass() {
        $this->actionIndex($this->setWhere(array(
                    'status' => 1,
                    'admin_id' => self::$uid,
        )));
    }

    //待审核列表
    public function actionCheck() {
        if ($_GET['getcheck']) {
            //$this->error('系统随机分配已经关闭！');
            $cat_id = (int) $_GET['cat_id'];
            if (empty($cat_id)) {
                $this->error('请先选择对应栏目！');
            }
            //时间段检测 8:30到18:30
            $time = time();
            if ($time < strtotime(date('Y-m-d 08:30:00')) || $time > strtotime(date('Y-m-d 18:30:00'))) {
                $this->error('请在上班时间处理新的待审核商品！');
            }
            //检查还没有审核完的数据量是否满足50，没有的话自动分配20个，以时间倒序
            $model = GoodsBmModel::model();
            //当前还没有审核完数据总数
//            $count = $model->count($model->where(array(
//                        'admin_id' => self::$uid,
//                        'status' => 0,
//                        'pay_status' => 0,
//                        'isdelivery' => 0,
//            )));
            //小于50个自动分配数据
            if (/* $count < $this->waitHeckSum */ true) {
                $model->updateAll(array(
                    'admin_id' => self::$uid,
                        ), $model->where(array(
                            'admin_id' => 0,
                            'status' => 0,
                            'cat_id' => $cat_id,
                            'pay_status' => 0,
                            'special_id' => 0,
                            'isdelivery' => 0,
                            'item_type' => array('LT', 10),
                            'order' => 'add_time ASC',
                            'limit' => $this->waitHeckCount,
                )));
                $this->success('获取新的审核数据成功！', self::U('check'));
                return true;
            } else {
                $this->assign('waitSecond', 5000);
                $this->error('<font color="#FF0000">无法获取新的需要审核的数据。</font><br/>原因：您已经多达<font color="#FF0000">50</font>个以上未审核完成商品数据，请审核完后再申请分配审核数据！', self::U('check'));
            }
        }
        //自动跳转到自己主要负责的栏目
        if (!isset($_GET['cat_id'])) {
            $admin_catid = AdminCategoryModel::model()->getDefaultCatid(self::$uid);
            if ($admin_catid) {
                $this->redirect(self::U(Yii::app()->getController()->getAction()->id, array('cat_id' => $admin_catid)));
            }
        }
        $this->actionIndex($this->setWhere(array(
                    'status' => 0,
                    'admin_id' => self::$uid,
                    'order' => 'add_time asc',
        )));
    }

    //审核未通过的
    public function actionNotong() {
        $this->actionIndex($this->setWhere(array(
                    'status' => 2,
                    'admin_id' => self::$uid,
        )));
    }

    //邮寄商品
    public function actionMail() {
        $this->actionIndex($this->setWhere(array(
                    'status' => 3,
                    'admin_id' => self::$uid,
                        //'isdelivery' => array('IN', array(0, 1)),
        )));
    }

    //所有邮寄商品(不单单只看自己的)
    public function actionMailAll() {
        $this->actionIndex($this->setWhere(array(
                    'status' => 3,
                        //'isdelivery' => array('IN', array(0, 1)),
        )));
    }
    //付费
    public function actionPay() {
        $pay_status = $_GET['pay_status'];
        if (empty($pay_status)) {
            $pay_status = array(array('EGT', -2), array('NEQ', 0), 'AND');
        } else {
            $this->assign('paystatus', $pay_status);
        }
        $this->actionIndex($this->setWhere(array(
                    'pay_status' => $pay_status,
                        //'isdelivery' => array('IN', array(0, 1)),
        )));
    }

    //双11付费
    public function actionPay11() {
        $pay_status = $_GET['pay_status'];
        if (empty($pay_status)) {
            $pay_status = array(array('EGT', -2), array('NEQ', 0), 'AND');
        } else {
            $this->assign('paystatus', $pay_status);
        }
        $this->actionIndex($this->setWhere(array(
                    'pay_status' => $pay_status,
                    'is_11' => 1,
        )));
    }

    //京东报名
    public function actionJd() {
        $this->actionIndex($this->setWhere(array(
                    'item_type' => 11,
        )));
    }

    //确认退款
    public function actionRefund() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        //查询报名信息
        $data = GoodsBmModel::model()->findByPk($goods_id);
        if (empty($data)) {
            $this->error('该报名信息不存在！');
        }
        if ($data->pay_status != -1) {
            $this->error('该商品还没到退款环节！');
        }
        $data->pay_status = -2;
        if ($data->save()) {
            $this->success('确认退款成功！');
        } else {
            $this->error('退款失败！');
        }
    }

    //确认已收到邮寄样品
    public function actionDelivery() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        //查询报名信息
        $data = GoodsBmModel::model()->findByPk($goods_id);
        if (empty($data)) {
            $this->error('该报名信息不存在！');
        }
        if ($data->isdelivery == 2) {
            $this->error('该商品已收到了邮寄样品');
        }
        $data->isdelivery = 2;
        $data->status_savetime = time();
        if ($data->save(false, array('isdelivery'))) {
            $this->success('确认退款成功！');
        } else {
            $this->error('退款失败！');
        }
    }

    //编辑
    public function actionEditor() {
        if (IS_POST) {
            //是否在报名查询显示旺旺
            if (!isset($_POST['is_show_wangwang'])) {
                $_POST['is_show_wangwang'] = 0;
            }
            if (GoodsBmModel::model()->editor($_POST)) {
                //推广人，超管才可以
                if (Yii::app()->passport->isAdministrator()) {
                    if (isset($_POST['recommend']) && $_POST['recommend']) {
                        GoodsSpreadModel::model()->saveSpreadUser($_POST['goods_id'], $_POST['recommend']);
                    } else {
                        GoodsSpreadModel::model()->deleteSpread($_POST['goods_id']);
                    }
                }
                $this->success('修改成功！');
            } else {
                $error = GoodsBmModel::model()->getOneError();
                $this->error($error ? $error : '修改失败！');
            }
        } else {
            $goods_id = Yii::app()->request->getParam('goods_id');
            //查询报名信息
            $data = GoodsBmModel::model()->findByPk($goods_id);
            if (empty($data)) {
                if (IS_AJAX && $_GET['ajax']) {
                    exit('no');
                } else {
                    $this->error('该报名信息不存在！');
                }
            }
            if ($data->status == 1) {
                if (IS_AJAX && $_GET['ajax']) {
                    exit('status');
                } else {
                    $this->error('该商品已经审核通过，需要修改请到商品管理中修改！');
                }
            }
            $this->assign('data', $data);
            if ($_GET['ajax']) {
                $this->render('ajax_editor');
            } else {
                //推广人信息
                if (Yii::app()->passport->isAdministrator()) {
                    $recommend = GoodsSpreadModel::model()->find(GoodsBmModel::model()->where(array('goods_bm_id' => $goods_id)));
                    if (!empty($recommend)) {
                        $recommend = $recommend->userid;
                        $this->assign('recommend', $recommend);
                    }
                }
                $this->render();
            }
        }
    }

    //删除信息
    public function actionDelete() {
        $this->error('删除功能屏蔽，请设置为审核不通过！');
        $goods_id = Yii::app()->request->getParam('goods_id');
        //查询报名信息
        $data = GoodsBmModel::model()->findByPk($goods_id);
        if (empty($data)) {
            $this->error('该报名信息不存在！');
        }
        if ($data->status == 0 && empty($data->admin_id)) {
            $this->error('不能删除还没有审核的商品！');
        } else if ($data->admin_id && Yii::app()->passport->uid != $data->admin_id) {
            $this->error('该商品不能删除，管理员 ' . GoodsBmModel::model()->getByUidFindName($data->admin_id) . ' 正在审核！');
        } else if ($data->admin_id && $data->status != 2) {
            $this->error('该商品正审核中，无法删除！');
        } else if ($data->status && $data->status != 2) {
            $this->error('该商品正审核中，无法删除！');
        }
        if ($data->delete()) {
            $this->success('删除成功！');
        } else {
            $this->error('删除失败！');
        }
    }

    //操作日志
    public function actionLogs() {
        //搜索
        if (IS_POST) {
            foreach ($_POST as $k => $v) {
                if ($v == '') {
                    unset($_POST[$k]);
                }
            }
            $this->redirect(AdminBase::U('logs', $_POST));
            exit;
        }
        $where = array(
            'action_type&product_id' => array('GT', 0),
            //'action_type' => array('IN',array(1,2,4,5)),
            'order' => 'id desc',
        );
        //状态
        $action_type = (int) $_GET['action_type'];
        if ($action_type) {
            $where['action_type'] = (int) $action_type;
            $this->assign('action_type', $action_type);
        }
        //时间
        $start_time = $_GET['start_time'];
        $end_time = $_GET['end_time'];
        if ($start_time) {
            $this->assign('start_time', $start_time);
            $this->assign('end_time', $end_time);
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time) + 86399;
            $where['action_time'] = array('EGT', $start_time);
            if ($end_time > $start_time) {
                $where['action_time'] = array(array('EGT', $start_time), array('ELT', $end_time), 'and');
            }
        }
        //管理员
        $admin_id = (int) $_GET['admin_id'];
        if ($admin_id) {
            $where['admin_id'] = $admin_id;
            $this->assign('admin_id', $admin_id);
        }
        //商品ID
        $product_id = $_GET['product_id'];
        if ($product_id) {
            $where['product_id'] = $product_id;
            $this->assign('product_id', $product_id);
        }

        //分页
        $pageId = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        //分页数
        $limit = 20;
        //报名模型
        $model = GoodsActionModel::model();
        $criteria = $model->where($where);
        //信息总数
        $count = $model->count($criteria);
        //分页
        $page = AdminBase::page($count, $limit, $pageId);
        //查询信息
        $criteria->limit = $page->listRows;
        $criteria->offset = $page->firstRow;
        $dataObj = $model->findAll($criteria);
        $data = array();
        foreach ($dataObj as $rs) {
            $data[$rs->id] = $rs->attributes;
            $data[$rs->id]['item'] = GoodsActionModel::model()->getCommodity($rs);
        }
        $this->assign("Page", $page->show());
        $this->assign('data', $data);
        $this->assign('count', $count);
        $this->assign('where', $where);
        $this->render();
    }

    //设置谁审核，也就是修改admin_id字段
    public function actionAdmin_check() {
        $goods_id = (int) $_GET['goods_id'];
        if (empty($goods_id)) {
            $this->error('该商品不存在！');
        }
        $admin_id = (int) $_GET['admin_id'];
        $model = GoodsBmModel::model()->findByPk($goods_id);
        if (empty($model)) {
            $this->error('该商品不存在！');
        }
        if ($model->admin_id && $model->status != 0) {
            $this->error('对不起，该宝贝已经有客服人员在洽谈，请审核其它宝贝！');
        }
        $model->admin_id = $admin_id ? $admin_id : self::$uid;
        $model->status_savetime = time();
        if ($model->update()) {
            $this->success('设置成功！');
        } else {
            $this->error('设置失败！');
        }
    }

    //获取淘宝商品信息
    public function actionPublic_iteminfo() {
        $product_id = Yii::app()->request->getParam('product_id');
        if (empty($product_id)) {
            $this->error('请指定商品id！');
        }
        if (!is_numeric($product_id)) {
            $parse_url = parse_url($product_id);
            parse_str($parse_url['query'], $query);
            $product_id = $query['id'];
            if (empty($product_id)) {
                $this->error('请指定商品id！');
            }
        }
        $data = TaobaoApi::getInstance()->getItem($product_id);
        if (empty($data)) {
            $data = array('status' => 0);
        } else {
            $data['status'] = 1;
        }
        $this->ajaxReturn($data);
    }

    //快捷编辑后，ajax重新加载内容
    public function actionPublic_load() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        //查询报名信息
        $data = GoodsBmModel::model()->findByPk($goods_id);
        if (empty($data)) {
            exit('');
        }
        $this->assign('rs', $data);
        $this->render();
    }

    //把报名审核通过的发布到商品管理
    public function actionFogoods() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        $data = GoodsBmModel::model()->findByPk($goods_id);
        if (empty($data)) {
            $this->error('该信息不存在！');
        }
        if ($data->status != 1) {
            $this->error('该信息还没有审核通过，无法同步到商品管理！');
        }
        if (GoodsModel::model()->goodsBmAdd($data->attributes)) {
            $this->success('发布到商品管理成功！');
        } else {
            $error = GoodsModel::model()->getOneError();
            $this->error($error ? $error : '发布到商品管理失败！');
        }
    }

    //批量操作
    public function actionPublic_check() {
        $batch_type = (int) Yii::app()->request->getParam('batch_type');
        if (empty($batch_type)) {
            $this->error('请选中批量操作类型！');
        }
        if (!RBAC::authenticate('editor')) {
            $this->error('您没有操作此项权限！');
        }
        if (!IS_POST) {
            $this->error('操作失败！');
        }
        $ids = $_POST['ids'];
        if (empty($ids) || empty($ids[0]) || !is_array($ids)) {
            $this->error('请选中需批量操作的信息！');
        }
        $batch_note = '';
        if ($batch_type == 2) {
            //不通过要理由
            $batch_note = Yii::app()->request->getParam('batch_note');
            if (empty($batch_note)) {
                $this->error('不通过原因不能为空！');
            }
        }
        if (Yii::app()->session->get('public_check')) {
            $this->error('请不要重复操作！');
        } else {
            Yii::app()->session->add('public_check', 1);
        }
        foreach ($ids as $k => $goodsBmId) {
            $goobsModel = new GoodsBmModel();
            $data = $goobsModel->findByPK($goodsBmId);
            if (!empty($data)) {
                //不是自己的和没有分配的，不允许操作
                if ($data->admin_id != self::$uid || empty($data->admin_id)) {
                    continue;
                }
                $data = $data->attributes;
                if (!empty($data)) {
                    if ($batch_type == 1) {
                        $data['status'] = 1;
                    } else if ($batch_type == 2) {
                        $data['status'] = 2;
                        $data['note'] = $batch_note;
                    }
                    $goobsModel->editor($data);
                    unset($data, $goobsModel);
                }
            }
            unset($ids[$k]);
        }
        Yii::app()->session->remove('public_check');
        $this->success('批量处理完成');
    }

    //信息通知
    public function actionNotice() {
        $goods_id = Yii::app()->request->getParam('goods_id');
        //查询报名信息
        $data = GoodsBmModel::model()->findByPk($goods_id);
        if (empty($data)) {
            $this->error('该报名信息不存在！');
        }
        $notice = Yii::app()->request->getParam('notice');
        if (empty($notice)) {
            $this->error('通知内容不能为空！');
        }
        $userInfo = MembersModel::model()->getUserInfo((int) $data->uid);
        if (empty($userInfo['phone'])) {
            $this->error('手机号为空，无法发送！');
        }
        //在报名查询显示旺旺
        $data->is_show_wangwang = 1;
        $data->save();
        Sns::getInstance()->mobile($userInfo['phone'])->data($notice)->send();
        $this->success('发送成功！');
    }

    /**
     * 设置查询条件
     * @param array $newWhere 额外附件条件
     * @return array
     */
    private function setWhere($newWhere = array()) {
        //条件数组
        $where = array(
            'order' => 'goods_id desc',
            //不显示付费的
            'pay_status' => 0,
                //不显示邮寄样品中的
                //'isdelivery' => 0,
        );
        //状态
        if (isset($_GET['status']) && is_numeric($_GET['status'])) {
            $where['status'] = (int) $_GET['status'];
        } else {
            unset($_GET['status']);
        }
        //上架时间
        if (isset($_GET['start_time']) && $_GET['start_time']) {
            $start_time = strtotime($_GET['start_time']);
            if ($_GET['end_time']) {
                $end_time = strtotime($_GET['end_time']) + 86399;
            }
            if ($start_time) {
                $where['start_time'] = array('EGT', $start_time);
            }
            if ($end_time > $start_time) {
                $where['start_time'] = array(array('EGT', $start_time), array('ELT', $end_time), 'and');
            } else if ($end_time && $end_time <= $start_time) {
                $where['start_time'] = array(array('EGT', $start_time), array('ELT', $start_time + 86399), 'and');
            }
        }
        //宝贝添加时间
        if (isset($_GET['add_start_time']) && $_GET['add_start_time']) {
            $add_start_time = strtotime($_GET['add_start_time']);
            if ($_GET['add_end_time']) {
                $add_end_time = strtotime($_GET['add_end_time']) + 86399;
            }
            if ($add_start_time) {
                $where['add_time'] = array('EGT', $add_start_time);
            }
            if ($add_end_time > $add_start_time) {
                $where['add_time'] = array(array('EGT', $add_start_time), array('ELT', $add_end_time), 'and');
            } else if ($end_time && $end_time <= $add_start_time) {
                $where['add_time'] = array(array('EGT', $add_start_time), array('ELT', $add_start_time + 86399), 'and');
            }
        }
        //关键字
        if (!empty($_GET['keyword'])) {
            $keyword = trim($_GET['keyword']);
            $type = (int) $_GET['type'];
            switch ($type) {
                case 1://商品ID
                    $where['product_id'] = $keyword;
                    break;
                case 2://商品名称
                    $where['goods_name'] = array('LIKE', "%{$keyword}%");
                    break;
                case 3://商品旺旺
                    $where['nick'] = array('LIKE', "%{$keyword}%");
                    break;
                default:
                    $where['product_id'] = $keyword;
                    break;
            }
        }
        //栏目
        if (!empty($_GET['cat_id'])) {
            $where['cat_id'] = (int) $_GET['cat_id'];
        }
        //审核人
        if (!empty($_GET['admin_id'])) {
            $where['admin_id'] = (int) $_GET['admin_id'];
        }
        if (!empty($newWhere) && is_array($newWhere)) {
            foreach ($newWhere as $k => $rs) {
                if (is_string($rs)) {
                    $_GET[$k] = $rs;
                }
            }
            $where = array_merge($where, $newWhere);
        }
        $this->assign($_GET);
        return $where;
    }

    //报名列表
    public function actionSpecial() {
        $objModel = new GoodsBmModel('search');
        $objModel->resetAttributes();
        if (isset($_GET['GoodsBmModel'])) {
            $type = isset($_GET['type']) ? $_GET['type'] : '';
            $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';
            switch ($type) {
                case 1:
                    $objModel->product_id = $keyword;
                    break;
                case 2:
                    $objModel->goods_name = $keyword;
                    break;
                case 3:
                    $objModel->nick = $keyword;
                    break;
            }
            $objModel->attributes = $_GET['GoodsBmModel'];
        }
        $objCriteria = $objModel->createSearchCriteria();

        $objCriteria->addCondition('special_id != 0');

        if (!Yii::app()->passport->isAdministrator()) {
            $objCriteria->addCondition('pay_status = 0');
        }

        //使用后台分页 
        $intCount = GoodsBmModel::model()->count($objCriteria);
        $pageId = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = 20;
        $page = self::page($intCount, $limit, $pageId);
        $strPage = $page->show();
        $objCriteria->limit = $page->listRows;
        $objCriteria->offset = $page->firstRow;

        //排序
        $objSort = new CSort('GoodsBmModel');
        $objSort->defaultOrder = 'goods_id DESC';
        $objSort->applyOrder($objCriteria);

        $objModels = GoodsBmModel::model()->findAll($objCriteria);
        $this->assign($_GET);
        $this->assign('pages', $strPage);
        $this->assign('model', $objModel);
        $this->assign('count', $intCount);
        $this->assign('models', $objModels);

        $this->render('special');
    }

    //设置谁审核，也就是修改admin_id字段//批量处理
    public function actionAdminSpecial() {
        if (isset($_POST['operation'])) {
            if (empty($_POST['ids'])) {
                $this->error('请选择操作的商品');
            }
            switch ($_POST['operation']) {
                case 0:
                    $this->error('请选择取消或分配');
                    break;
                case 1:
                    $admin_id = 0;
                    break;
                case 2:
                    $admin_id = isset($_POST['admin_id_operation']) ? $_POST['admin_id_operation'] : '';
                    if (!$admin_id) {
                        $this->error('请选择分配的操作员');
                    }
                    break;

                default:
                    $this->error('访问错误');
                    break;
            }
            $arrAttributes = array(
                'admin_id' => $admin_id,
                'status_savetime' => time(),
            );

            $goods_id = implode(',', $_POST['ids']);

            $strCondition = "status = 0 AND goods_id in({$goods_id})";
            if (GoodsBmModel::model()->updateAll($arrAttributes, $strCondition)) {
                $this->success('设置成功');
            } else {
                $this->success('没有变化');
            }
        }
    }

    public function actionPublic_opengoodslist() {

        $goods_id = Yii::app()->request->getParam('goods_id');
        $is_count = isset($_GET['count']) ? $_GET['count'] : '';
        $objModel = GoodsBmModel::model()->findByPk($goods_id);
        if ($is_count) {
            //统计
            $arr = array();
            $arrData = $objModel->getGoodsNumbers($goods_id, 1);
            $arr['status_shangjia'] = $arrData['count'];
            $arrData = $objModel->getGoodsNumbers($goods_id, '');
            $arr['status_baoming'] = $arrData['count'];
            echo json_encode($arr);
            exit;
        } else {
            $status = isset($_GET['status']) ? $_GET['status'] : '';
            $page = isset($_GET['page']) ? $_GET['page'] : 1;
            $limit = 20;

            $arrData = $objModel->getGoodsNumbers($goods_id, $status, $page, $limit);
            $count = $arrData['count'];

            $page = self::page($count, $limit, $page);
            $strPage = $page->show();

            $this->assign('pages', $strPage);
            $this->assign('count', $count);
            $this->assign('models', $arrData['data']);

            $this->render();
        }
    }

}
